package cn.edu.jxau.core.util;

import cn.edu.jxau.core.exception.ReflectException;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Desc:
 * ------------------------------------
 * Author:fulei04@meituan.com
 * Date:2017/12/15
 * Time:下午2:31
 */
public class ReflectUtils {

    public static <T> T newInstance(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }

    public static Object invokeMethod(Method method, Object target, Object... params) {

        method.setAccessible(true);
        try {
            return method.invoke(target, params);
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }

    public static Method getMethod(Class clazz,String methodName, Class<?>... parameterTypes) {

        try {
            return clazz.getMethod(methodName,parameterTypes);
        } catch (NoSuchMethodException e) {
            throw new ReflectException(e);
        }
    }

    public static void setField(Field field, Object target, Object newValue) {

        field.setAccessible(true);
        try {
            field.set(target, newValue);
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }

    public static Object getField(Field field, Object target) {

        field.setAccessible(true);
        try {
            return field.get(target);
        } catch (Exception e) {
            throw new ReflectException(e);
        }
    }
}
